"use client";

import React, { useState, useRef, useEffect } from 'react';
import { Button, Upload, message, Image } from 'antd';
import { PictureOutlined, DeleteOutlined, ExpandOutlined } from '@ant-design/icons';
import { RcFile, UploadFile } from 'antd/es/upload/interface';
import { UploadChangeParam } from 'antd/es/upload';
import { uploadFileUsingPost } from '@/api/fileController';

interface ImageUploadProps {
  onImageUpload: (url: string) => void;
  onImageRemove: () => void;
  imageUrl?: string;
}

const ImageUpload: React.FC<ImageUploadProps> = ({ onImageUpload, onImageRemove, imageUrl }) => {
  const [previewImage, setPreviewImage] = useState<string | null>(imageUrl || null);
  const [file, setFile] = useState<RcFile | null>(null);
  
  // 当文件状态改变时，处理上传
  useEffect(() => {
    if (file) {
      handleUpload(file);
    }
  }, [file]);
  
  // 处理图片上传
  const handleUpload = async (file: RcFile) => {
    console.log("开始上传文件到服务器:", file.name);
    
    try {
      // 调用后端API上传文件
      const response = await uploadFileUsingPost(
        { biz: 'interview' }, // params
        {}, // body
        file // file
      );
      
      if (response.data) {
        console.log("图片上传成功:", response.data);
        // 上传成功后隐藏预览区域
        setPreviewImage(null);
        onImageUpload(response.data);
        message.success('图片上传成功');
      } else {
        throw new Error('上传失败');
      }
    } catch (error) {
      console.error("文件上传过程中发生错误:", error);
      message.error('图片上传失败，请重试');
    }
  };
  
  // 删除已选择的图片
  const handleRemoveImage = () => {
    if (previewImage) {
      URL.revokeObjectURL(previewImage);
    }
    setFile(null);
    setPreviewImage(null);
    onImageRemove();
    message.success('图片已删除');
  };
  
  // 处理上传前的验证
  const beforeUpload = (file: RcFile) => {
    console.log("beforeUpload 被调用，文件:", file.name, "类型:", file.type);
    
    // 验证文件格式
    const isImageFile = file.type?.startsWith('image/');
    const validImageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg', 'image/webp'];
    
    if (!isImageFile || !validImageTypes.includes(file.type || '')) {
      message.error('请上传正确的图片格式 (JPEG, PNG, GIF, JPG, WEBP)');
      return Upload.LIST_IGNORE;
    }
    
    // 生成随机文件名
    const fileExtension = file.name.split('.').pop() || '';
    const randomFileName = `${Math.random().toString(36).substring(2, 15)}.${fileExtension}`;
    const renamedFile = new File([file], randomFileName, { type: file.type });
    
    // 设置文件状态，将在useEffect中处理上传
    try {
      console.log("设置文件状态:", renamedFile.name);
      setFile(renamedFile as RcFile);
    } catch (err) {
      console.error("处理文件失败:", err);
      message.error("图片选择失败，请重试");
    }
    
    return false; // 阻止自动上传，我们会在发送消息时上传
  };
  
  return (
    <>
      {/* 图片预览区域 */}
      {previewImage && (
        <div className="image-preview">
          <div className="preview-wrapper">
            <Image 
              src={previewImage} 
              alt="预览图片" 
              className="preview-image"
              preview={{
                maskClassName: 'preview-image-mask',
                mask: <div><ExpandOutlined /></div>
              }}
            />
            <Button
              type="text"
              danger
              icon={<DeleteOutlined />}
              className="remove-image-btn"
              onClick={handleRemoveImage}
            />
          </div>
        </div>
      )}
      
      {/* 上传按钮 */}
      {!previewImage && (
        <Upload
          showUploadList={false}
          beforeUpload={beforeUpload}
          accept="image/jpeg,image/png,image/gif,image/jpg,image/webp"
          maxCount={1}
        >
          <Button
            icon={<PictureOutlined />}
            type="text"
            title="上传图片"
            className="upload-button"
          />
        </Upload>
      )}
    </>
  );
};

export default ImageUpload;